﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace EasyBackupService.Utils
{
    public static class Log
    {
        public static void Clear()
        {
            try
            {
                string[] logFiles = Directory.GetFiles(App.LogDir);
                DateTime minDate = DateTime.Now.AddDays(-7);

                foreach (string logFile in logFiles)
                {
                    if (File.GetCreationTime(logFile) < minDate || File.GetLastWriteTime(logFile) < minDate)
                        File.Delete(logFile);
                }
            }
            catch
            { 
            }
        }

        public static void CheckDir()
        {
            if (!Directory.Exists(App.LogDir))
                Directory.CreateDirectory(App.LogDir);
        }

        public static void Write(string msg)
        {
            try
            {
                if (!string.IsNullOrEmpty(msg) && msg.EndsWith(".."))
                    msg = msg.Remove(msg.Length - 1);

                string message = DateTime.Now + "\t" + msg + Environment.NewLine;
                string fileName = App.LogDir + @"\" + DateTime.Now.ToShortDateString() + ".txt";
                File.AppendAllText(fileName, message);

                FileInfo f = new FileInfo(fileName);
                if ((f.Length / 1024f) / 1024f > 2f)
                {
                    f.Delete();
                }
            }
            catch
            {
            }
        }

        public static void Info(string infoMessage, string from, string to, string logTime)
        {
            Write(infoMessage + " from " + from + " to " + to + " scheduled for " + logTime + ".");
        }

        public static void Error(string errorMessage, string from, string to, string logTime)
        {
            Write("An error occurred during the backup from " + from + " to " + to + " scheduled for " + logTime + ". Error message: " + errorMessage + ".");
        }
    }
}
